import logging

from django.core.mail import send_mail
from django_redis import get_redis_connection

from qqmall.settings import EMAIL_HOST_USER
from utils.resFormatUyil import FormatResponse
from celery_tasks.celery_main import app

loger = logging.getLogger(__name__)

EMAIL_KEY = 'email:%s'

@app.task(name='send_mail_task')
def send_mail_task(email, random_code, expiry):
    '''
    :param eamil: 发送的邮箱对象
    :param random_code: 发送到验证码
    :param expiry: 验证码过期时间
    :return:
    '''
    try:
        data = {
            'subject': 'qqmall',
            'message': '',
            'html_message': f'''
            <h1>qqmall购物中心<h1>
            <p>欢迎注册qqmall购物中心会员<p>
            <p>您的验证码为{random_code}<p>
            <p>有效时间为{expiry}分钟<p>
            ''',
            'from_email': EMAIL_HOST_USER,
            'recipient_list': [email],
        }
        res = send_mail(**data)
    except Exception as e:
        loger.error(f'[邮箱账号为{email}]:[邮件发送异常，错误信息为{e}]')
    else:
        if res != 1:
            loger.error(f'[邮箱账号为{email}]:[邮件接受异常]')
        else:
            # 将验证码保存到redis数据库中
            cache_default = get_redis_connection()
            cache_default.set(EMAIL_KEY % email,random_code,expiry*60)



# import logging
#
# from django.core.mail import send_mail
# from django_redis import get_redis_connection
#
# from qqmall.settings import EMAIL_HOST_USER
# from celery_tasks.celery_main import app
#
# logger = logging.getLogger(__name__)
#
# EMAIL_KEY = 'email:verify:%s'
#
# @app.task(name='send_mail_task')
# def send_mail_task(email, verify, expiry):
#     try:
#         data = {
#             'subject': 'nsygsc-VPN',
#             'message': '',
#             'html_message': f'''
#                 <h3>这里是wsnd的vpn注册中心</h3>
#                 <p>验证码为{verify}</p>
#                 <p>有效时间为{expiry}分钟，请在有效时间内注册</p>
#                 ''',
#             'from_email': EMAIL_HOST_USER,
#             'recipient_list': [email]
#         }
#         res = send_mail(**data)
#     except Exception as e:
#         logger.error('邮件发送异常，[email:%s,error:%s]'%(email,e))
#     else:
#         if res != 1:
#             logger.warning('邮件接收异常,[email:%s]'%email)
#         else:
#             logger.info('邮件发送成功')
#             # 将验证码储存到数据库中
#             cache = get_redis_connection(alias='verify_code')
#             cache.set(EMAIL_KEY % email,verify,expiry*60)
#             cache_default = get_redis_connection()
#             cache_default.set(email,'1',60)
#
